package org.xyl.game.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.xyl.game.dao.MyGameDao;
import org.xyl.game.dao.RoomDao;
import org.xyl.game.dao.StartDao;
import org.xyl.game.dto.UpdateCountRet;
import org.xyl.game.entity.Mygame;
import org.xyl.game.entity.Room;
import org.xyl.game.entity.Start;
import org.xyl.game.service.MyGameService;

import java.util.List;

@Service
public class MyGameServiceImpl implements MyGameService {

    @Autowired
    private MyGameDao myGameDao;
    @Autowired
    private StartDao startDao;

    @Autowired
    private RoomDao roomDao;

    @Override
    @Transactional
    public boolean startGame(int roomid) {
        Start byRoomid = startDao.getByRoomid(roomid);
        byRoomid.setFlag(1);
        Start save = startDao.save(byRoomid);
        return true;
    }

    @Override
    public boolean finishGame(int roomid, String username, int mycount, String result) {
        Mygame mygame = new Mygame();
        mygame.setRoomid(roomid);
        mygame.setUsername(username);
        mygame.setMycount(mycount);
        mygame.setResult(result);
        Mygame save = myGameDao.save(mygame);
        if (save != null) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public List<Mygame> historyGame(String username) {
        return myGameDao.getByUsernameOrderByRoomidAsc(username);
    }

    @Override
    @Transactional
    public UpdateCountRet updateCount(int roomid, String team, int count) {
        Room byRoomid = roomDao.getByRoomid(roomid);
        if (team.equals("red")) {
            byRoomid.setRedcount(byRoomid.getRedcount() + count);
        } else {
            byRoomid.setBluecount(byRoomid.getBluecount() + count);
        }
        roomDao.save(byRoomid);
        UpdateCountRet updateCountRet = new UpdateCountRet();
        updateCountRet.setRedcount(byRoomid.getRedcount());
        updateCountRet.setBluecount(byRoomid.getBluecount());
        return updateCountRet;
    }
}
